import { message } from 'antd';
import { createAction, handleActions } from 'redux-actions';
import axios from '../../services/axiosConfig';
import history from '../../services/history';

// action-type
const types = {
    loginSuccess: '/SysUser/Syslogin'
}

// reducer
const reducers = {};
const initialState = {
    ifLogin: false,
    userName: ''
}

reducers[types.loginSuccess] = (state, action) => {
    let userName = action.payload;
    return { ...state, ifLogin: true, userName }
}

export const auth = handleActions(reducers, initialState);

// action
const loginSuccess = createAction(types.loginSuccess);
export const loginAction = (params) => async(dispatch) => {
    let res = await axios.post('/SysUser/Syslogin', params);
    if (res.data.success) {
        await dispatch(loginSuccess(params.userName));
        history.push('/index');
    } else {
        message.error(res.data.error);
    }
}

